/*
 * @Description: 统一的结果返回拦截器
 * @Author: lihk
 * @Date: 2024-09-24 16:30:42
 */
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

interface ResponseData<T> {
  code: number;
  data: T;
  msg: string;
}
@Injectable()
export class ResponseInterceptor<T> implements NestInterceptor<T, ResponseData<T>> {
  intercept(context: ExecutionContext, next: CallHandler): Observable<ResponseData<T>> {
    const http = context.switchToHttp();
    const request = http.getRequest();
    const response = http.getResponse();

    return next.handle().pipe(
      map(data => {
        // 如果是 POST 请求，则设置状态码为 200
        if (request.method === 'POST') {
          response.statusCode = 200;
        }
        return {
          code: response.statusCode,
          data,
          msg: response.statusCode === 200 ? 'Success' : 'Error'
        };
      })
    );
  }
}
